// pages/Tabbar/Protocol/Protocol.js
//获取应用实例
const app = getApp();
import { queryUserIou } from '../../../api/protocol';
import { getBrandConfig } from '../../../api/brand';
import { throttle } from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    page: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    dataList: [],
    userId: wx.getStorageSync('userId'),
    closeDay: '',
    tabList: [
      { id: '1', name: '借给我'},{ id: '2', name: '我借出'},
    ],
    active: '1',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getBrandConfig();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      dataList: [],
    })
    this.getData();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._getGoods()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  _getBrandConfig(){
    let _this = this;
    getBrandConfig({})
    .then(res => {
      if(res.success){
        _this.setData({
          closeDay: res.data[0].iouAutoCloseDay ?? 30,
        })
        _this.getData();
      }else{
        wx.showToast
      }
    })
  },
  onTabChange(e){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      active: e.detail.name,
    })
    this.getData();
  },
  // 获取数据
  getData(){
    let _this = this;
    const { active } = _this.data;
    var userId = wx.getStorageSync('userId');
    queryUserIou({page: _this.data.page,lendUserId: active == '2' ? userId : '',borrowUserId: active == '1' ? userId : ''})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        let arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const element = res.data.content[index];
          var itemTime = element.createTime.replace(/-/g,'/')
          var createTime = new Date(itemTime).getTime();
          var nowTime = new Date().getTime();
          var diffTime = createTime - nowTime + parseInt(_this.data.closeDay) * 24 * 3600 * 1000;
          if(diffTime < 0 && element.status == '0'){
            element.status = '2'
          }
          element.diffTime = diffTime;
          arr.push(element);
        }
        if(_this.data.page == 0){
          list = arr;
        }else{
          list = list.concat(arr);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  detail(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    var url = item.status == '0' ? '/pages/Protocol/ProtocolShareDetail/ProtocolShareDetail' : '/pages/Protocol/ProtocolDetail/ProtocolDetail'
    wx.navigateTo({
      url: `${url}?protocolId=${item.id}`,
      events: {
        'updateProtocol': function(data){
          this.setData({
            page: 0,
            isReachBottom: false,
            noMore: false,
            loading: false,
            loadingFailed: false,
            dataList: [],
          })
          this.getData();
        }
      }
    })
  },
})